Telegram Group & Telegram Channel
🧵 RAII — главный секрет устойчивого к утечкам C++ кода

Привет! Сегодня хочу напомнить о технике, без которой невозможно писать безопасный и устойчивый C++ код — это RAII (Resource Acquisition Is Initialization).

RAII — это идиома, в которой захват ресурса (файл, сокет, память, мьютекс) происходит в конструкторе объекта, а освобождение — в деструкторе. Благодаря этому ресурсы освобождаются автоматически, даже при исключениях.

Пример:


#include <fstream>

void saveData(const std::string& filename) {
std::ofstream file(filename); // открытие файла
if (!file.is_open())
throw std::runtime_error("Cannot open file");

file << "some data"; // файл закроется автоматически
}


RAII делает твой код:
Безопасным к утечкам
Устойчивым к исключениям
Лёгким для чтения и сопровождения

💡 Совет: всегда оборачивай "ручные" ресурсы в обёртки — std::unique_ptr, std::lock_guard, std::ofstream, std::thread и т.д.


➡️ @cpp_geek



tg-me.com/cpp_geek/295
Create:
Last Update:

🧵 RAII — главный секрет устойчивого к утечкам C++ кода

Привет! Сегодня хочу напомнить о технике, без которой невозможно писать безопасный и устойчивый C++ код — это RAII (Resource Acquisition Is Initialization).

RAII — это идиома, в которой захват ресурса (файл, сокет, память, мьютекс) происходит в конструкторе объекта, а освобождение — в деструкторе. Благодаря этому ресурсы освобождаются автоматически, даже при исключениях.

Пример:


#include <fstream>

void saveData(const std::string& filename) {
std::ofstream file(filename); // открытие файла
if (!file.is_open())
throw std::runtime_error("Cannot open file");

file << "some data"; // файл закроется автоматически
}


RAII делает твой код:
Безопасным к утечкам
Устойчивым к исключениям
Лёгким для чтения и сопровождения

💡 Совет: всегда оборачивай "ручные" ресурсы в обёртки — std::unique_ptr, std::lock_guard, std::ofstream, std::thread и т.д.


➡️ @cpp_geek

BY C++ geek




Share with your friend now:
tg-me.com/cpp_geek/295

View MORE
Open in Telegram


C geek Telegram | DID YOU KNOW?

Date: |

The Singapore stock market has alternated between positive and negative finishes through the last five trading days since the end of the two-day winning streak in which it had added more than a dozen points or 0.4 percent. The Straits Times Index now sits just above the 3,060-point plateau and it's likely to see a narrow trading range on Monday.

Telegram and Signal Havens for Right-Wing Extremists

Since the violent storming of Capitol Hill and subsequent ban of former U.S. President Donald Trump from Facebook and Twitter, the removal of Parler from Amazon’s servers, and the de-platforming of incendiary right-wing content, messaging services Telegram and Signal have seen a deluge of new users. In January alone, Telegram reported 90 million new accounts. Its founder, Pavel Durov, described this as “the largest digital migration in human history.” Signal reportedly doubled its user base to 40 million people and became the most downloaded app in 70 countries. The two services rely on encryption to protect the privacy of user communication, which has made them popular with protesters seeking to conceal their identities against repressive governments in places like Belarus, Hong Kong, and Iran. But the same encryption technology has also made them a favored communication tool for criminals and terrorist groups, including al Qaeda and the Islamic State.

C geek from ye


Telegram C++ geek
FROM USA